import { useState, useEffect } from 'react'
import { Editor } from '@tiptap/react'

export const useAutoSave = (editor: Editor | null, chapterId?: string) => {
  const [lastSavedContent, setLastSavedContent] = useState<string>('')
  const [autoSaveInterval] = useState<number>(5000) // 每5秒保存一次
  
  useEffect(() => {
    if (!editor || !chapterId) return
    
    const interval = setInterval(() => {
      const currentContent = editor.getHTML()
      
      // 如果内容变化且非空，则保存
      if (currentContent !== lastSavedContent && currentContent.trim() !== '') {
        console.log('自动保存章节内容...')
        // 在这里实现具体的保存逻辑，比如调用API或更新本地存储
        // 例如: saveChapterContent(chapterId, currentContent)
        setLastSavedContent(currentContent)
      }
    }, autoSaveInterval)
    
    return () => clearInterval(interval)
  }, [editor, chapterId, lastSavedContent, autoSaveInterval])
  
  return {
    lastSavedContent
  }
} 